<template>
  <view class="transfer-detail-container">
    <!-- 头部信息卡片 -->
    <view class="header-card">
      <view class="detail-item">
        <view class="item-label">转移单号</view>
        <view class="item-value">{{ detailData.transferCode || '' }}</view>
      </view>
      
      <view class="detail-item">
        <view class="item-label">转移单名称</view>
        <view class="item-value">{{ detailData.transferName || '' }}</view>
      </view>
      
      <view class="detail-item">
        <view class="item-label">转移人</view>
        <view class="item-value">{{ detailData.transferUserName || '' }}</view>
      </view>
      
      <view class="detail-item">
        <view class="item-label">接收人</view>
        <view class="item-value">{{ detailData.receiveUserName || '' }}</view>
      </view>
      
      <view class="detail-item">
        <view class="item-label">转移日期</view>
        <view class="item-value">{{ detailData.transferDate || '' }}</view>
      </view>
      
      <view class="detail-item">
        <view class="item-label">接收位置</view>
        <view class="item-value">{{ detailData.receiveLocationName || '' }}</view>
      </view>
      
      <view class="detail-item">
        <view class="item-label">备注</view>
        <view class="item-value">{{ detailData.remark || '' }}</view>
      </view>
      
      <view class="detail-item">
        <view class="item-label">接收管理员</view>
        <view class="item-value">{{ detailData.receiveManagerName || '' }}</view>
      </view>
    </view>
    
    <!-- 资产列表 -->
    <view class="assets-section">
      <view class="section-header">
        <view class="section-title">资产列表</view>
        <view class="section-count">共计: {{ assetList.length }}</view>
      </view>
      
      <view class="assets-list">
        <view class="asset-item" v-for="(item, index) in assetList" :key="index">
          <view class="asset-image">
            <image :src="item.image ? `${BASE_URL}/File/GetImage?fileId=${item.image}` : '/static/placeholder.png'" mode="aspectFill"></image>
          </view>
          <view class="asset-info">
            <view class="asset-name">{{ item.assetName }}</view>
            <view class="asset-detail">资产分类: {{ item.assetClassName }}</view>
            <view class="asset-detail">资产编码: {{ item.assetCode }}</view>
            <view class="asset-detail">规格型号: {{ item.specModel }}</view>
            <view class="asset-detail">转移位置: {{ item.transferLocation }}</view>
            <view class="asset-detail">标签编码: {{ item.labelCode || '' }}</view>
          </view>
          <view class="asset-status">
            <view class="status-tag status-transferred">{{ item.assetStateName }}</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 普通模式下的底部返回按钮 -->
    <view class="footer-button" v-if="!isAuditMode">
      <view class="btn-back" @click="goBack">返回</view>
    </view>
    
    <!-- 审核模式下的底部按钮 -->
    <view class="footer-audit" v-if="isAuditMode">
      <up-button type="default" text="驳回" @click="showRejectDialog"></up-button>
      <up-button type="primary" text="通过" @click="approveTransfer"></up-button>
    </view>
    
    <!-- 驳回原因弹窗 -->
    <up-popup :show="showRejectPopup" :round="10" mode="center" @close="closeRejectDialog" @open="onRejectPopupOpen">
      <view class="reject-popup">
        <view class="reject-title">驳回原因</view>
        <view class="reject-content">
          <up-textarea
            v-model="rejectReason"
            placeholder="请输入驳回原因"
            :maxlength="200"
          ></up-textarea>
        </view>
        <view class="reject-buttons">
          <up-button type="default" text="取消" @click="closeRejectDialog"></up-button>
          <up-button type="primary" text="确定" @click="confirmReject"></up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import http, { BASE_URL } from "@/api/request";
import { t } from "@/locale/index.js"

// 详情数据
const detailData = ref({
  transferCode: '',
  transferName: '',
  transferUserName: '',
  receiveUserName: '',
  transferDate: '',
  receiveLocationName: '',
  remark: '',
  receiveManagerName: ''
});

// 资产列表
const assetList = ref([]);

// 页面参数
const pageParams = ref({
  transferCode: '',
  mode: ''
});

// 审核相关状态
const isAuditMode = ref(false);
const showRejectPopup = ref(false);
const rejectReason = ref('');

// 页面加载
onLoad((options) => {
  
  if (options.transferCode) {
    pageParams.value.transferCode = options.transferCode;
    // 判断是否为审核模式
    isAuditMode.value = options.mode === 'audit';
  }
  if(isAuditMode.value){
    uni.setNavigationBarTitle({
      title: t("assetTransfer.audit")
    });
  }else{
    uni.setNavigationBarTitle({
      title: t("assetTransfer.detail")
    });
  }
  loadTransferDetail(options.transferCode);
});

// 加载转移单详情
const loadTransferDetail = (transferCode) => {
  uni.showLoading({
    title: '加载中...'
  });
  
  http.post('/api/module/Invoke', {
    pageCode: 'assettransfer',
    params: {
      args: [
        {
          name: 'interfaceCode',
          value: 'assettransfer.getAssetTransferOrderDetail'
        },
        {
          name: 'transferCode',
          value: transferCode
        }
      ]
    },
    methodName: 'getAssetTransferOrderDetail'
  }).then(res => {
    uni.hideLoading();
    
    if (res.isSuccess && res.result) {
      const { masterInfo, assetDetails } = res.result;
      
      // 填充主信息
      detailData.value = {
        transferCode: masterInfo.transferCode || '',
        transferName: masterInfo.transferName || '',
        transferUserName: masterInfo.transferUserName || '',
        receiveUserName: masterInfo.receiverUserName || '', // 修正字段名
        transferDate: masterInfo.transferDate || '',
        receiveLocationName: masterInfo.receiverLocationName || '', // 修正字段名
        remark: masterInfo.remark || '',
        receiveManagerName: masterInfo.receiverAdminName || '' // 修正字段名
      };
      
      // 填充资产列表
      if (assetDetails && Array.isArray(assetDetails)) {
        assetList.value = assetDetails.map(item => ({
          id: item.id,
          assetCode: item.assetCode,
          assetName: item.assetName,
          assetClassName: item.assetClassName,
          specModel: item.specModel,
          transferLocation: item.location || detailData.value.receiveLocationName,
          labelCode: item.labelNumber, // 修正字段名
          image: item.image,
          status: item.assetState,
          assetStateName:item.assetStateName
        }));
      }
    } else {
      uni.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('加载转移单详情失败:', err);
    uni.hideLoading();
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示驳回原因弹窗
const showRejectDialog = () => {
  rejectReason.value = '';
  showRejectPopup.value = true;
};

// 关闭驳回原因弹窗
const closeRejectDialog = () => {
  showRejectPopup.value = false;
};

// 弹窗打开事件
const onRejectPopupOpen = () => {
  console.log('驳回弹窗已打开');
};

// 确认驳回
const confirmReject = () => {
  if (!rejectReason.value.trim()) {
    uni.showToast({
      title: '请输入驳回原因',
      icon: 'none'
    });
    return;
  }
  rejectTransfer();
  closeRejectDialog();
};

// 审核通过
const approveTransfer = () => {
  uni.showModal({
    title: '审核确认',
    content: `确定通过转移单 ${pageParams.value.transferCode} 的审核吗？`,
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        // 调用审核通过接口
        submitAudit('APPROVED');
      }
    }
  });
};

// 驳回转移单
const rejectTransfer = () => {
  // 调用驳回接口
  submitAudit('REJECTED');
};

// 提交审核结果
const submitAudit = (auditResult) => {
  uni.showLoading({
    title: '提交中...'
  });
  
  const data = { 
    pageCode: "assettransfer", 
    params: { 
      args: [ 
        { 
          name: "interfaceCode", 
          value: "assettransfer.approveAssetTransferOrder" 
        }, 
        { 
          name: "transferCode", 
          value: pageParams.value.transferCode
        },
        {
          name: "auditState",
          value: auditResult === 'APPROVED' ? 'APPROVED' : 'REJECTED'
        }
      ] 
    }, 
    methodName: "approveAssetTransferOrder" 
  };
  console.log(data);
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();
    console.log(res);
    if (res.isSuccess) {
      uni.showToast({
        title: auditResult === 'APPROVED' ? '审核通过成功' : '驳回成功',
        icon: 'success'
      });
      
      // 触发列表页面数据刷新
      uni.$emit('data-changed');
      
      // 延迟返回，确保提示信息显示完成
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.error || '操作失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('审核操作失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};
</script>

<style lang="scss" scoped>
.transfer-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;

  .header-card {
    // background: linear-gradient(135deg, #4792FD 0%);
    background-color: #4792FD;
    margin: 20rpx;
    border-radius: 12rpx;
    padding: 30rpx;
    color: #fff;

    .detail-item {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .item-label {
        width: 180rpx;
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.8);
      }

      .item-value {
        flex: 1;
        font-size: 28rpx;
        color: #fff;
        font-weight: 500;
      }
    }
  }

  .assets-section {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 12rpx;
    padding: 30rpx;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .section-title {
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
      }

      .section-count {
        font-size: 26rpx;
        color: #666;
      }
    }

    .assets-list {
      .asset-item {
        display: flex;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #eee;
        position: relative;

        &:last-child {
          border-bottom: none;
        }

        .asset-image {
          width: 120rpx;
          height: 120rpx;
          margin-right: 20rpx;
          position: relative;

          image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }
        }

        .asset-info {
          flex: 1;

          .asset-name {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 8rpx;
            font-weight: 500;
          }

          .asset-detail {
            font-size: 24rpx;
            color: #666;
            margin-top: 4rpx;
          }
        }

        .asset-status {
          position: absolute;
          top: 20rpx;
          right: 0;

          .status-tag {
            padding: 8rpx 16rpx;
            border-radius: 20rpx;
            font-size: 22rpx;
            color: #fff;

            &.status-transferred {
              background-color: #52c41a;
            }

            &.status-pending {
              background-color: #faad14;
            }

            &.status-received {
              background-color: #1890ff;
            }
          }
        }
      }
    }
  }

  .footer-button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .btn-back {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      color: #fff;
      background-color: #4792FD;
      border-radius: 40rpx;
    }
  }
  
  /* 审核模式下的底部按钮 */
  .footer-audit {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-around;
  }
  
  /* 驳回弹窗样式 */
  .reject-popup {
    width: 600rpx;
    padding: 30rpx;
  }

  .reject-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .reject-content {
    margin-bottom: 30rpx;
  }

  .reject-buttons {
    display: flex;
    justify-content: space-between;
  }

}
</style>
